package com.sscl.blelibrary;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;


/**
 * Broadcast receiver detecting Bluetooth switch status
 *
 * @author jackie
 */
final class BleScannerBluetoothStateReceiver extends BroadcastReceiver {

    /*-----------------------------------field variables-----------------------------------*/

    /**
     * BLE scanner
     */
    @Nullable
    private BleScanner bleScanner;

    /*-----------------------------------Constructor-----------------------------------*/

    /**
     * Constructor
     *
     * @param bleScanner BleScanner
     */
    BleScannerBluetoothStateReceiver(@NonNull BleScanner bleScanner) {
        this.bleScanner = bleScanner;
    }

    /*-----------------------------------Override method-----------------------------------*/

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action == null) {
            return;
        }
        //noinspection SwitchStatementWithTooFewBranches
        switch (action) {
            case BluetoothAdapter.ACTION_STATE_CHANGED:
                int bluetoothState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
                switch (bluetoothState) {
                    case BluetoothAdapter.STATE_OFF:
                        if (bleScanner != null) {
                            bleScanner.stopScan();
                        }
                        break;
                    case BluetoothAdapter.STATE_ON:
                        BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
                        if (bluetoothManager == null) {
                            return;
                        }
                        if (bleScanner != null) {
                            bleScanner.setBluetoothAdapter(bluetoothManager.getAdapter());
                        }
                        break;
                    default:
                        break;
                }
                break;
            default:
                break;
        }
    }

    /*-----------------------------------package private method-----------------------------------*/

    /**
     * Free memory
     */
    void releaseData() {
        bleScanner = null;
    }
}
